package com.cgy.service.Impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.cgy.entity.Student;
import com.cgy.entity.Xibie;
import com.cgy.repository.studentRepository;
import com.cgy.service.StudentService;


@Service
public class StudentServiceImpl implements StudentService {
	
	@Autowired
	private studentRepository stuR; 

	
	@Override
	public Page<Student> findBysnamePage(Student s, Pageable pageable) {
		// TODO Auto-generated method stub
		return stuR.findAll(get(s), pageable);
	}
	private Specification<Student> get(Student s){
		return new Specification<Student>() {
			
			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				Predicate predicate = criteriaBuilder.conjunction();//动态sql表达式
				List<Expression<Boolean>> exList = predicate.getExpressions(); 
				//多条件查询 如果sname不为空 添加sql
				if(!StringUtils.isEmpty(s.getSname())) {
					exList.add(criteriaBuilder.like(root.get("sname"),"%"+s.getSname()+"%"));
				}
				//xid是外键 所以需要调用系别中的xid 
				if(s.getXibie().getXid()!=null) {
					exList.add(criteriaBuilder.equal(root.get("xibie").get("xid"),s.getXibie().getXid()));
				}
				return predicate;
			}
		};
		
	}

	@Transactional
	@Override
	public Student addAndUpdate(Student s) {
		// TODO Auto-generated method stub
		return stuR.saveAndFlush(s);
	}
@Transactional
	@Override
	public Integer deleteStudentByID(Integer sid) {
		// TODO Auto-generated method stub
		return stuR.deleteStudentByID(sid);
	}
@Override//验证卡号
public List<Student> findLikecard(Integer scardid) {
	// TODO Auto-generated method stub 
	return stuR.findLikecard(scardid);
}
//根据卡号修改学生状态
@Override
public Integer upstudentstatus(Integer scardid) {
	// TODO Auto-generated method stub
	return stuR.upstudentstatus(scardid);
}
 
}
